using System;
using System.Globalization;
using System.Windows.Data;

namespace WPFServices.Converters
{
    /// <summary>
    /// 状态转换器 - 将数字状态转换为中文描述
    /// </summary>
    public class StatusConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return "未知";
            
            // 尝试获取整数值
            int? intValue = GetIntValue(value);
            
            if (!intValue.HasValue) return "未知";
            
            return intValue.Value switch
            {
                0 => "禁用",
                1 => "启用",
                _ => "未知"
            };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        private int? GetIntValue(object value)
        {
            if (value == null) return null;
            
            // 如果是非空整数
            if (value.GetType() == typeof(int))
            {
                return (int)value;
            }
            
            // 如果是可空整数
            if (value.GetType() == typeof(int?))
            {
                return (int?)value;
            }
            
            // 尝试字符串解析
            if (int.TryParse(value.ToString(), out int parsedInt))
            {
                return parsedInt;
            }
            
            return null;
        }
    }

    /// <summary>
    /// 状态颜色转换器 - 根据状态返回不同的颜色
    /// </summary>
    public class StatusColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null) return "#999999";
            
            // 尝试获取整数值
            int? intValue = GetIntValue(value);
            
            if (!intValue.HasValue) return "#999999";
            
            return intValue.Value switch
            {
                0 => "#FF5722", // 红色 - 禁用
                1 => "#4CAF50", // 绿色 - 启用
                _ => "#999999"  // 灰色 - 未知
            };
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
        
        private int? GetIntValue(object value)
        {
            if (value == null) return null;
            
            // 如果是非空整数
            if (value.GetType() == typeof(int))
            {
                return (int)value;
            }
            
            // 如果是可空整数
            if (value.GetType() == typeof(int?))
            {
                return (int?)value;
            }
            
            // 尝试字符串解析
            if (int.TryParse(value.ToString(), out int parsedInt))
            {
                return parsedInt;
            }
            
            return null;
        }
    }
} 